package com.aier.admin.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.aier.admin.entity.IcCard;
import com.aier.admin.entity.mapper.IcCardRowMapper;
import com.aier.admin.service.IAdminAssignCardService;
import com.aier.common.common.Constant;
import com.aier.common.dao.ICommonDAO;
import com.aier.entrance.common.EntranceICFinalData;
import com.aier.proxy.entity.ProxyIcard;
import com.aier.proxy.entity.mapper.ProxyIcardRowMapper;

@Component("adminAssignCardService")
public class AdminAssignCardServiceImpl_J implements IAdminAssignCardService {

    @Resource(name = "commonDao")
    private ICommonDAO commonDao;

    public void setCommonDao(ICommonDAO commonDao) {
        this.commonDao = commonDao;
    }

    @Override
    public Map<String, Object> searchAssignCard(Short icstate0, Short icstate1,
            int page, int page_size) {
        if (null == icstate0 || null == icstate1) {
            return null;
        }
        StringBuffer sql = new StringBuffer(
                "select * from ic_card ic where ic.icstate=? or ic.icstate=?");
        List<Object> lo = new ArrayList<Object>();
        lo.add(icstate0);
        lo.add(icstate1);
        return commonDao.queryPage(sql.toString(), page, page_size, lo,
                new IcCardRowMapper());
    }

    /**
     * 查询分派给代理商的卡
     */
    @Override
    public Map<String, Object> searchAssignProxyCard(Short icstate10,
            Integer pid, int page, int page_size) {
        if (null == icstate10) {
            return null;
        }
        StringBuffer sql = new StringBuffer(
                "select * from ic_card where icstate=? and icid in (select icid from proxy_icard where pid=?)");
        List<Object> lo = new ArrayList<Object>();
        lo.add(icstate10);
        lo.add(pid);
        return commonDao.queryPage(sql.toString(), page, page_size, lo,
                new IcCardRowMapper());
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<IcCard> searchCard(String name, String icbody1, String icbody2) {
        return (List<IcCard>) commonDao
                .list("select * from ic_card ic where ic.icbody between ? and ? and ic.ichead=? and (ic.icstate=? or ic.icstate=?)",
                        new Object[] { icbody1, icbody2, name,
                            EntranceICFinalData.IC_STATE_SYS_NOT_ACTIVE,
                            EntranceICFinalData.IC_STATE_SYS_ACTIVE },
                        new IcCardRowMapper());
    }

    @Override
    public int insertCard(Long cid, Integer pid) {
        ProxyIcard proxyIcard = new ProxyIcard();
        proxyIcard.setIcid(cid);
        proxyIcard.setPid(pid);
        commonDao.insert("proxy_icard", ProxyIcardRowMapper.getArgs(
                new HashMap<String, Object>(), proxyIcard));
        return 0;
    }

    @Override
    public int updateCardProxy(String name, String icbody1, String icbody2,
            Integer pid) {
        try {
            List<IcCard> icCards2 = searchCard(name, icbody1, icbody2);
            for (int i = 0; i < icCards2.size(); i++) {
                Long cid = icCards2.get(i).getIcid();
                insertCard(cid, pid);
                commonDao
                        .update("update ic_card set icstate=? where icid=?",
                                new Object[] {
                                    EntranceICFinalData.IC_STATE_PROXY, cid });
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<IcCard> searchProxyCard() {
        return (List<IcCard>) commonDao.list(
                "select * from  ic_card where icstate=? ",
                new Object[] { EntranceICFinalData.IC_STATE_PROXY },
                new IcCardRowMapper());
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<IcCard> searchSchoolCard() {
        return (List<IcCard>) commonDao.list(
                "select * from  ic_card where icstate=? ",
                new Object[] { EntranceICFinalData.IC_STATE_SCHOOL },
                new IcCardRowMapper());
    }

    /**
     * 回收代理商手中未分派的卡
     * 
     * @param name
     *            卡前缀
     * @param icbody1
     *            卡中部
     * @param icbody2
     *            卡尾部
     * @param pid
     *            代理商id
     * @return
     */
    @Override
    public int deleteAssignProxyCard(String name, String icbody1,
            String icbody2, Integer pid) {

        try {
            List<IcCard> icCards = searchIcCards(name, icbody1, icbody2, pid);
            for (int i = 0; i < icCards.size(); i++) {
                Long cid = icCards.get(i).getIcid();
                commonDao.update("update ic_card set icstate=? where icid=?",
                        new Object[] { EntranceICFinalData.IC_STATE_SYS_ACTIVE,
                            cid });

            }
        } catch (Exception e) {
            e.printStackTrace();
            return Constant.num_10000;
        }

        if(commonDao
                .update("delete from proxy_icard where pid=? and icid in (select icid from ic_card " +
                        "where icstate=? and icbody between ? and ? and ichead=?)",
                        new Object[] { pid, EntranceICFinalData.IC_STATE_SYS_ACTIVE,
                            icbody1, icbody2, name })>0){
            return Constant.num_10001;
        }else{
            return Constant.num_10000;
        }
        

    }

    /**
     * 查询成功回收的IC卡
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<IcCard> searchRecoverProxyCards(String name, String icbody1,
            String icbody2, Integer pid) {

        return (List<IcCard>) commonDao
                .list("select * from  ic_card where icid in (select icid from proxy_icard where pid=?) " +
                        "and icid in (select icid from ic_card where icstate=? and icbody between ? and ? and ichead=?)",
                        new Object[] { pid, EntranceICFinalData.IC_STATE_PROXY,
                            icbody1, icbody2, name }, new IcCardRowMapper());
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<IcCard> searchIcCards(String name, String icbody1,
            String icbody2, Integer pid) {

        return (List<IcCard>) commonDao
                .list("select icid from ic_card where icstate=? and icbody between ? " +
                        "and ? and ichead=? and icid in (select icid from proxy_icard where pid=?)",
                        new Object[] { EntranceICFinalData.IC_STATE_PROXY,
                            icbody1, icbody2, name, pid },
                        new IcCardRowMapper());
    }

    @Override
    public int insertCardSchool(Integer sid, String cardnum) {
        IcCard ic = (IcCard) commonDao.listByObject("select * from ic_card where ichead = ? and icbody = ?", 
                new Object[]{cardnum.substring(0, 2),cardnum.substring(2,Constant.num_8)}, new IcCardRowMapper());
        if (ic != null) {
            // 已分派给学校，要先回收
            if (ic.getIcstate() == Constant.num_60 || ic.getIcstate() == Constant.num_90) {
                return 2;
            } else {
                commonDao.update("update ic_card set icstate = 60 where icid = ?", new Object[]{ic.getIcid()});
            }
        } else {
            // 先录入卡
            return Constant.num_3;
        }
        
        // 分派给学校
        commonDao.update("insert into school_icard(sid,icid,state,bsdate) values (?,?,?,?)",
                new Object[]{sid,ic.getIcid(),Constant.num_10,new Timestamp(new Date().getTime())});
        
        return 1;
    }

    @Override
    public int updateCardRecover(String cardnum) {
        IcCard ic = (IcCard) commonDao.listByObject("select * from ic_card where ichead = ? and icbody = ?", 
                new Object[]{cardnum.substring(0, 2),cardnum.substring(2,Constant.num_8)}, new IcCardRowMapper());
        if (ic == null) {
            // 卡未录入系统中
            return 2;
        }
        commonDao.update("delete from school_icard where icid = ?", new Object[]{ic.getIcid()});
        commonDao.update("update ic_card set icstate = 1 where icid = ?", new Object[]{ic.getIcid()});
        commonDao.update("delete from school_student_icard where icid = ?", new Object[]{ic.getIcid()});
        commonDao.update("delete from school_teacher_icard where icid = ?", new Object[]{ic.getIcid()});
        return 1;
    }

}
